import { usePrevious } from 'ahooks';
import React, { useEffect, useState, useCallback } from 'react';
import styles from './switchThemeFile.less';
import theme1 from '@/assets/theme1.less';
import theme2 from '@/assets/theme2.less';
import theme3 from '@/assets/theme3.less';

const themeModules = [theme1, theme2, theme3];

/**
 * 按照参数数组依次切换item，到最后一个回到第一个
 */
function useSwitch(list: any[]) {
  const [index, setIndex] = useState(0);
  const next = useCallback(() => {
    setIndex(current => {
      const next = list[current + 1];
      return next ? current + 1 : 0;
    });
  }, []);
  return [list[index], next];
}

/**
 * 按照指定的 theme css module 来切换 html 类，从而切换不同的变量集合
 */
function useApplyTheme(theme: any) {
  const previousTheme = usePrevious(theme);
  useEffect(() => {
    const html = document.getElementsByTagName('html')[0];
    if (previousTheme) {
      html.classList.remove(previousTheme.theme);
    }
    html.classList.add(theme.theme);
  }, [theme]);
}

function BlockWithOwnTheme() {
  const [themeModule, toggle] = useSwitch(themeModules);
  return (
    <div
      className={styles.block + ' ' + themeModule.theme}
      onMouseDown={toggle}
    >
      {themeModule.theme}
    </div>
  );
}

export default function() {
  const [themeModule, toggle] = useSwitch(themeModules);
  useApplyTheme(themeModule);
  return (
    <div className={styles.normal}>
      <h1>Page switchThemeFile</h1>
      <button onClick={toggle}>切换</button>
      <div className={styles.div}>text</div>
      <div>下面是分区域设置和切换主题变量的div,每个区域</div>
      <div className={styles.flexWraper}>
        <BlockWithOwnTheme />
        <BlockWithOwnTheme />
        <BlockWithOwnTheme />
      </div>
    </div>
  );
}
